package cn.middle.basic.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.middle.common.base.mapper.BaseMapper;
import com.middle.common.base.service.impl.BaseServiceImpl;
import com.middle.common.result.Page;

import cn.middle.basic.entity.SysRole;
import cn.middle.basic.mapper.SysRoleMapper;
import cn.middle.basic.service.SysRoleService;

@Service
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole> implements SysRoleService {
	
	@Autowired
	private SysRoleMapper sysRoleMapper;

	@Override
	public List<SysRole> findRolesByUserId(Long userId) {
		return sysRoleMapper.rolesByUser(userId);
	}

	@Override
	public BaseMapper<SysRole> getDao() {
		return sysRoleMapper;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Page<SysRole> listByCodeOrName(int page, int pageSize, String code, String name) {
		PageHelper.startPage(page,pageSize);
		List<SysRole> roles = sysRoleMapper.rolesByCodeOrName(code, name);
		return new Page(new PageInfo<SysRole>(roles));
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void associationRolePermissions(Long roleId, List<Long> permissionIds) {
		//先解除关系
		sysRoleMapper.disarmPermissions(roleId);
		//重新关联
		for(Long permissionId : permissionIds) sysRoleMapper.associationRolePermission(roleId, permissionId);
	}

	@Override
	public boolean hasAssociationRole(Long roleId) {
		return sysRoleMapper.associationRoleTotal(roleId) > 0;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void disarmPermissionsAndDelete(Long roleId) {
		sysRoleMapper.disarmPermissions(roleId);
		sysRoleMapper.deleteByPrimaryKey(roleId);
	}

	@Override
	public boolean occupiedCode(String code) {
		return sysRoleMapper.occupiedCode(code) > 0;
	}

	@Override
	public List<Long> associationRolePermissions(Long roleId) {
		return sysRoleMapper.associationRolePermissions(roleId);
	}

}
